import { HttpException, HttpStatus } from '@nestjs/common';
import * as ErrorCode from './error.code';

type ErrorType = (typeof ErrorCode)[keyof typeof ErrorCode];

// 取状态码，这里规定 key 中_后的值为状态码
export function getErrorCode(errorType: ErrorType) {
  const key = Object.keys(ErrorCode).find((key) => ErrorCode[key] === errorType);
  return key ? +key.split('_')[1] : -1;
}

/** 自定义异常 */
export class CustomException extends HttpException {
  protected code: number;

  constructor(errorType: ErrorType, message?: string, status?: HttpStatus) {
    message = message ?? errorType;
    super(message, status ?? HttpStatus.BAD_REQUEST);
  }
}
export { ErrorCode };
